﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Exentials.Xoox.Spreadsheet
{
    public class XSharedStringTable : XElementList<XElementBase>
    {
        internal class XStringItem : XElementBase
        {
            private XElementBase _text;

            public XStringItem()
                : base("si")
            {
                this.Add(_text = new XElementBase("t"));
            }

            public string Text
            {
                get
                {
                    return _text.GetXElement().Value;
                }
                set
                {
                    _text.GetXElement().SetValue(value);
                }
            }

            public override string ToString()
            {
                return Text;
            }
        }

        private XAttributeBase<int> _uniqueCount;

        public XSharedStringTable() :
            base("sst")
        {
            _uniqueCount = new XAttributeBase<int>(this, "uniqueCount") { Value = 0 };
        }

        public int Add(string text, bool shared)
        {
            int index;
            XElementBase element = this.Where(t => t.ToString() == text).FirstOrDefault();

            if (element == null)
            {
                index = base.Add(new XStringItem() { Text = text });
                _uniqueCount.Value++;
            }
            else if (!shared)
            {
                index = base.Add(new XStringItem() { Text = text });
            }
            else
            {
                index = (int)this.IndexOf(element);
            }

            return index;
        }

        public int UniqueCount
        {
            get { return _uniqueCount.Value; }
        }
    }
}
